import { Component, ViewChild } from '@angular/core';
import { ICellEditorAngularComp } from '@ag-grid-community/angular';
import { ApesTimePickerComponent } from '@shared/apes/time-picker';
import { dateFormat } from '../../../utils/utils';

@Component({
  selector: 'apes-cell-time',
  template: `
    <div>
      <apes-time-picker #picker [apesFormat]="formatType" (ngModelChange)="onChange($event)"
                        (apesOpenChange)="setValue($event)"
                        [(ngModel)]="inputValue"></apes-time-picker>
    </div>
  `,
  styles: [],
})
export class EditorTimeComponent implements ICellEditorAngularComp {
  inputValue: any;
  params: any;
  ctx: any;
  // yyyy-MM-dd  yyyy-MM-dd HH:mm:ss  yyyy-MM-dd HH:mm:ss SSS
  formatType: string = 'HH:mm:ss';

  @ViewChild('picker', { read: ApesTimePickerComponent, static: false }) picker: ApesTimePickerComponent;

  constructor() {
  }

  agInit(params: any): void {
    this.params = params;
    let downFormatter;
    if (params.hasOwnProperty('colDef')) {
      downFormatter = params.colDef['downFormatter'];
    } else {
      downFormatter = params.column['colDef']['downFormatter'];
    }
    if(downFormatter){
      this.formatType = downFormatter;
    }
    if (params.value) {
      // let date;
      // if(this.formatType == 'HH:mm' || this.formatType == 'HH:mm:ss'){
      //   date = dateFormat('yyyy-MM-dd',new Date()) +' '+ params.value;
      // }else {
      //   date = params.value
      // }
      // this.inputValue =  new Date(date);
      this.inputValue =  new Date(params.value);
    } else {
      this.inputValue = new Date();
    }
  }

  ngAfterViewInit() {
    this.picker.apesOpen = true;
  }

  isPopup(): boolean {
    return false;
  }

  getValue(): any {
    let result;
    if (!this.inputValue) {
      result = '';
      this.params.value = '';
    } else {
      // result = dateFormat(this.formatType, new Date(this.inputValue));
      result = new Date(this.inputValue);
      this.params.value = this.inputValue;
    }
    return result;
  }

  onKeyDown(event): void {
    this.preventDefaultAndPropagation(event);
    let key = event.which || event.keyCode;
    if (key === 38 || key === 40) {

    } else if (key == 13 || key == 9) { // enter
      // perform some validation on enter - in this example we assume all inputs are mandatory
      // in a proper application you'd probably want to inform the user that an input is blank'
      /**/
      this.inputValue = event.target.value;
      this.params.value = event.target.value;
    }
  }

  onChange(param) {
    this.inputValue = param;//dateFormat(this.formatType, new Date(param));
    this.params.value = param;
  }

  setValue(param) {
    this.params.stopEditing(true);
    this.preventDefaultAndPropagation(event);
  }

  private preventDefaultAndPropagation(event) {
    event.preventDefault();
    event.stopPropagation();
  }
}
